package com.company.chatRoom;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    聊天室服务器端
 */
public class ChatServer {
    public static List<Socket> sockets = new ArrayList<>();
    private static String userName = "服务端";
    private static Thread sendThread;
    private static Thread listenThread;
    public static void main(String[] args) {
        try {
            System.out.println("Socket服务器开始运行");
            ServerSocket serverSocket = new ServerSocket(9999);
            sendThread = new Thread(new ServerSend(userName));
            sendThread.start();
            while (true){
                //接收客户端请求
                Socket socket = serverSocket.accept();
                sockets.add(socket);
                listenThread = new Thread(new ServerListen(socket));
                listenThread.start();
            }
        }catch (Exception e){
            closeAllThread();
            e.printStackTrace();
        }
    }


    public static List<Socket> getSockets() {
        return sockets;
    }

    public static void setSockets(List<Socket> sockets) {
        ChatServer.sockets = sockets;
    }

    public static String getUserName() {
        return userName;
    }

    public static void setUserName(String userName) {
        ChatServer.userName = userName;
    }

    public static void closeAllThread(){
        if(listenThread.isAlive()){
            listenThread.interrupt();
            System.out.println("listenThread断开连接");
        }
        if(sendThread.isAlive()){
            sendThread.interrupt();
            System.out.println("sendThread断开连接");
        }
    }
}
